const express = require('express');
const router = express.Router();
const authenticateToken = require('../middleware/auth');

// 获取可领取的优惠券模板
router.get('/templates', (req, res) => {
  const query = `
    SELECT 
      id,
      name,
      type,
      value,
      min_amount as minAmount,
      max_discount as maxDiscount,
      total_count as totalCount,
      used_count as usedCount,
      (total_count - used_count) as remaining,
      start_time as startTime,
      end_time as endTime,
      status
    FROM coupon_templates 
    WHERE status = 'ACTIVE' 
    AND (total_count - used_count) > 0
    ORDER BY created_at DESC
    LIMIT 1
  `;

  global.db.query(query, (err, results) => {
    if (err) {
      console.error('获取优惠券模板失败:', err);
      return res.status(500).json({ message: '获取优惠券模板失败' });
    }

    console.log(`找到${results.length}个可领取模板`);
    
    res.json({
      message: '获取成功',
      templates: results
    });
  });
});

// 领取优惠券
router.post('/receive/:templateId', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  const templateId = req.params.templateId;

  console.log(`用户${userId}领取模板${templateId}`);

  // 检查模板是否存在且可用
  const checkTemplate = `
    SELECT * FROM coupon_templates 
    WHERE id = ? AND status = 'ACTIVE' 
    AND (total_count - used_count) > 0
  `;

  global.db.query(checkTemplate, [templateId], (err, templates) => {
    if (err) {
      console.error('查询模板失败:', err);
      return res.status(500).json({ message: '查询优惠券模板失败' });
    }

    if (templates.length === 0) {
      return res.status(400).json({ message: '优惠券模板不存在或已失效' });
    }

    const template = templates[0];

    // 检查用户是否已经领取过
    const checkReceived = 'SELECT * FROM user_coupons WHERE user_id = ? AND template_id = ?';
    global.db.query(checkReceived, [userId, templateId], (err, received) => {
      if (err) {
        console.error('检查用户优惠券失败:', err);
        return res.status(500).json({ message: '检查用户优惠券失败' });
      }

      if (received.length > 0) {
        return res.status(400).json({ message: '您已经领取过这张优惠券了' });
      }

      // 创建用户优惠券
      const insertCoupon = `
        INSERT INTO user_coupons (
          user_id, template_id, name, type, value, min_amount, max_discount,
          status, start_time, end_time
        ) VALUES (?, ?, ?, ?, ?, ?, ?, 'UNUSED', ?, ?)
      `;

      const values = [
        userId, templateId, template.name, template.type, template.value,
        template.min_amount, template.max_discount, template.start_time, template.end_time
      ];

      global.db.query(insertCoupon, values, (err, result) => {
        if (err) {
          console.error('创建用户优惠券失败:', err);
          return res.status(500).json({ message: '领取优惠券失败' });
        }

        // 更新模板使用次数
        const updateTemplate = 'UPDATE coupon_templates SET used_count = used_count + 1 WHERE id = ?';
        global.db.query(updateTemplate, [templateId], (err) => {
          if (err) {
            console.error('更新模板使用次数失败:', err);
          }
        });

        console.log(`用户${userId}成功领取${template.name}`);
        res.json({ message: '领取成功' });
      });
    });
  });
});

// 获取用户优惠券列表
router.get('/', authenticateToken, (req, res) => {
  const userId = req.user.userId;
  
  const query = `
    SELECT 
      id,
      template_id as templateId,
      name,
      type,
      value,
      min_amount as minAmount,
      max_discount as maxDiscount,
      status,
      start_time as startTime,
      end_time as endTime,
      received_at as receivedAt,
      used_at as usedAt,
      (end_time < NOW()) as isExpired
    FROM user_coupons 
    WHERE user_id = ? 
    ORDER BY received_at DESC
  `;

  global.db.query(query, [userId], (err, results) => {
    if (err) {
      console.error('获取用户优惠券失败:', err);
      return res.status(500).json({ message: '获取用户优惠券失败' });
    }

    res.json({
      message: '获取成功',
      coupons: results
    });
  });
});

module.exports = router;



